package com.leilei;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * @author lei
 * @version 1.0
 * @date 2021/3/7 15:51
 * @desc 单词计数 DataStream lambda表达式
 */
public class WordCountDataStream2 {
    public static void main(String[] args) {
        try {
            // 1.准备环境
            StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
            // 设置运行模式
            env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
            //env.setRuntimeMode(RuntimeExecutionMode.BATCH);
            //env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
            // 2.准备数据源
            //DataStreamSource<String> elementsSource = env.fromElements("java,scala,php,c++",
            //        "java,scala,php", "java,scala", "java");
            DataStreamSource<String> elementsSource = env.socketTextStream("xxxx", 9999);
            // 3.数据处理 lambda表达式导致泛型丢失，所以需要returns指定，否则会启动报错
            SingleOutputStreamOperator<String> flatMap = elementsSource
                    .flatMap((String element, Collector<String> out) -> Arrays.stream(element.split(","))
                            .forEach(out::collect))
                    .returns(Types.STRING);
            //  lambda表达式导致泛型丢失，所以需要returns指定，否则会启动报错
            DataStream<Tuple2<String, Integer>> streamOperator = flatMap.map(word -> Tuple2.of(word, 1))
                    .returns(Types.TUPLE(Types.STRING,Types.INT));
            KeyedStream<Tuple2<String, Integer>, String> groupStream = streamOperator.keyBy(value -> value.f0);
            SingleOutputStreamOperator<Tuple2<String, Integer>> sum = groupStream.sum(1);
            sum.writeAsText("/root/wordCount.txt");
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
